package com.oolee.cloud.lb;



import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;


import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyLoadBalancer implements LoadBalance {


    //原子封装类
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    /**
     * 计算得到当前调用次数
     * @return
     */
    public final int getAndIncrement(){
        int current;
        int next;

        do {
            current = atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current+1;
        }while (!atomicInteger.compareAndSet(current,next));   //利用CAS保证原子操作

        return next;
    }


    /**
     * 轮询算法
     * 当前调用数 % 服务实例数量
     * @param serviceInstances
     * @return
     */
    @Override
    public ServiceInstance getInstance(List<ServiceInstance> serviceInstances) {
        int index = this.getAndIncrement() % serviceInstances.size();
        //根据下标返回对应的服务实例
        return serviceInstances.get(index);
    }
}
